﻿(function () {
    RaidFight = {};
    var guaiArr = [];
    var _publicCd = true;

    RaidFight.Instance = {
        Init: function () {
            $(document).on('click', '.jineng', this.JinengActick);
            $(document).on('click', '#closeResult', this.CloseResult);
        },
        //注册怪AI攻击
        InitMonsterAiAttack: function () {
            for (var i = 0; i < MonsterModel.CurrentFight.length; i++) {
                //注册
                this.BindMonsterAttackEvent(MonsterModel.CurrentFight[i]);
            }
        },
        CloseResult:function(){
            layer.closeAll();
        },
        BindMonsterAttackEvent: function (monsterModel) {
            var fightId = $("#fightId").val();
            var attackInterval = setInterval(function () {

                if ($("#monster_" + monsterModel.Id + "").html() == undefined)
                    clearInterval(attackInterval);
                if ($("#monster_" + monsterModel.Id + "").parent().css("visibility") == "hidden")
                    clearInterval(attackInterval);

                if ($("#zhujiao").html() == undefined)
                    clearInterval(attackInterval);
                if (_fightStatus == -1)
                    clearInterval(attackInterval);
                //判断有没有技能，有技能放技能，必须在CD内
                var type = 1;
                if (monsterModel.IsHasSkill == 1) {
                    if (parseInt($("#monster_" + monsterModel.Id + "").attr("skillCd")) == 0) {//判断是否在Cd内
                        type = 2;
                    }
                }
                var roleObj = RaidModel.Model.CreateHeroModel();
                webExpress.utility.ajax.request("/Raid/RaidMonsterFight?token=" + ToolManager.Common.Token(), { "fightId": fightId, "heroId": UserBase.Status.HeroId, "monsterId": monsterModel.Id, "type": type }, function (data) {
                    if (data.IsSuccess) {

                        //如果是技能，转冷却cd
                        if (type == 2) {
                            RaidFight.Instance.ControlMonsterSkillCd(monsterModel);
                        }
                        var skill = new MonsterSkill(monsterModel, type, roleObj);
                        skill.CreateSkill();
                        skill.MoveTarget();
                        setTimeout(RaidFight.Instance.RaidMonsterBloodControlCall(data.Data), 500);
                    }
                });
            }, monsterModel.ApInteral * 1000)

        },
        //技能整合
        JinengActick: function () {

            var jinengId = $(this).attr("SkillId");
            //判断当前技能是否在冷却时间和公共CD时间
            if ($("#cd_" + jinengId + "").length > 0 || !_publicCd) {
                return false;
            }
            var fightId = $("#fightId").val();
            //服务器战斗，返回成功，客户端执行动画。
            webExpress.utility.ajax.request("/Raid/RaidFight?token=" + ToolManager.Common.Token(), { "fightId": fightId, "heroId": UserBase.Status.HeroId, "skillId": jinengId }, function (data) {
                if (data.IsSuccess) {
                    var skillModel = SkillModel.Bussiness.GetSkillModel(jinengId);
                    var jinengCd = skillModel.CdTime;
                    RaidFight.Instance.TriggerPublicCd(1000);
                    RaidFight.Instance.ShowCd(jinengId, jinengCd);
                    if (skillModel.SkillOption == 1) {
                        RaidFight.Instance.InitGuai();
                        //--伤害
                        if (skillModel.SkillType == 1) {
                            //--一次性伤害效果技能
                            var specialEffectType = skillModel.SpecialEffectType;
                            switch (specialEffectType) {
                                case 1://单体技能攻击，有路径
                                    var monster = guaiArr[0];
                                    var skill = new Skill(skillModel, 1000, monster);
                                    skill.CreateModel();
                                    skill.Move();
                                    setTimeout(RaidFight.Instance.RaidBloodControlCall(data.Data, skillModel.SkillOption, 1), 500);
                                    break;
                                case 3:////群体技能攻击，左右冲击

                                    var skill = new Skill(skillModel, 1000);
                                    skill.CreateModel();
                                    skill.MoveBig();
                                    setTimeout(RaidFight.Instance.RaidBloodControlCall(data.Data, skillModel.SkillOption, 1), 800);
                                    break;
                                case 4://单体技能攻击，无路径，直接怪物脚下出来
                                    var monster = guaiArr[0];
                                    var skill = new Skill(skillModel, 1000, monster);
                                    skill.CreateModelTarget(monster.Soft);
                                    skill.MoveTarget();
                                    setTimeout(RaidFight.Instance.RaidBloodControlCall(data.Data, skillModel.SkillOption, 1), 500);
                                    break;
                                case 5://群体技能攻击，无路径，直接从脚下出来
                                    for (var i = 0; i < guaiArr.length; i++) {
                                        var skill = new Skill(skillModel, 1000, guaiArr[i]);
                                        skill.CreateModelTarget(guaiArr[i].Soft);
                                        skill.MoveTarget();
                                    }
                                    setTimeout(RaidFight.Instance.RaidBloodControlCall(data.Data, skillModel.SkillOption, 1), 500);
                                    break;
                            }

                        } else {
                            //--持续性伤害技能效果
                            for (var i = 0; i < data.Data.Monsters.length; i++) {
                                var guid = ToolManager.Common.Token();
                                $("#monsterBuff_" + data.Data.Monsters[i].Id + "").append('<span><img style="height: 20px; width: 20px;" src="' + skillModel.SkillIcon + '" id="monsterBuff_' + guid + '" skillId="' + jinengId + '" fightId="' + fightId + '" monsterId="' + data.Data.Monsters[i].Id + '" skillTime="' + skillModel.SkillTime + '" /></span>');
                                RaidFight.Instance.DotEventBind(guid);
                            }

                        }
                    } else if (skillModel.SkillOption == 2) {
                        //--治疗
                        if (skillModel.SkillType == 1) {
                            //--一次性治疗效果技能
                            var roleObj = RaidModel.Model.CreateHeroModel();
                            var skill = new RoleCureSkill(skillModel, roleObj);
                            skill.CreateSkill();
                            skill.MoveTarget();
                            setTimeout(RaidFight.Instance.RaidBloodControlCall(data.Data, skillModel.SkillOption, 1), 500);
                        } else {
                            //--持续性治疗技能效果
                            var guid = ToolManager.Common.Token();
                            $("#buff").append('<span><img style="height: 20px; width: 20px;" src="' + skillModel.SkillIcon + '" id="roleBuff_' + guid + '" skillId="' + jinengId + '" fightId="' + fightId + '"  skillTime="' + skillModel.SkillTime + '" /></span>');
                            RaidFight.Instance.CureDotEventBind(guid);
                        }
                    }
                } else {
                    ToolManager.Layer.ErrorTimeMsg(data.Message, 2);
                }
            });
        },
        //治疗DOT事件绑定，每个DOT独立
        CureDotEventBind: function (guid) {
            var obj = $("#roleBuff_" + guid + "");
            var skillId = obj.attr("skillId");
            var fightId = obj.attr("fightId");
            var skillModel = SkillModel.Bussiness.GetSkillModel(skillId);
            var interval = setInterval(function () {
                if (_fightStatus == 1 || _fightStatus == -1)
                    clearInterval(interval);
                //服务器战斗，返回成功，客户端执行动画。
                webExpress.utility.ajax.request("/Raid/RoleDotSkillFight?token=" + ToolManager.Common.Token(), { "fightId": fightId, "heroId": UserBase.Status.HeroId, "skillId": skillId, "monsterId": 0 }, function (data) {
                    if (data.IsSuccess) {
                        RaidFight.Instance.RaidDotBloodControl(data, 0, skillModel);
                        var restTime = parseInt(obj.attr("skillTime")) - skillModel.IntervalTime;
                        if (restTime <= 0) {
                            obj.parent().remove();
                            clearInterval(interval);
                        } else {
                            obj.attr("skillTime", restTime);
                        }
                    }
                });

            }, skillModel.IntervalTime * 1000)
        },
        //伤害DOT伤害事件绑定,每个dot独立
        DotEventBind: function (guid) {
            var obj = $("#monsterBuff_" + guid + "");
            var skillId = obj.attr("skillId");
            var fightId = obj.attr("fightId");
            var monsterId = obj.attr("monsterId");
            var skillModel = SkillModel.Bussiness.GetSkillModel(skillId);
            var interval = setInterval(function () {
                if (_fightStatus == 1)
                    clearInterval(interval);
                if ($("#monster_" + monsterId + "").html() == undefined)
                    clearInterval(interval);
                if ($("#monster_" + monsterId + "").parent().css("visibility") == "hidden")
                    clearInterval(interval);
                //服务器战斗，返回成功，客户端执行动画。
                webExpress.utility.ajax.request("/Raid/RoleDotSkillFight?token=" + ToolManager.Common.Token(), { "fightId": fightId, "heroId": UserBase.Status.HeroId, "skillId": skillId, "monsterId": monsterId }, function (data) {
                    if (data.IsSuccess) {
                        if (data.Data.MonsterStatus != -1) {
                            RaidFight.Instance.RaidDotBloodControl(data, monsterId, skillModel);
                        }

                        if (data.Data.IsDead == 1) {
                            clearInterval(interval);
                        }
                        var restTime = parseInt(obj.attr("skillTime")) - skillModel.IntervalTime;

                        if (restTime <= 0) {
                            obj.parent().remove();
                            clearInterval(interval);
                        } else {
                            obj.attr("skillTime", restTime);
                        }
                    }
                });

            }, skillModel.IntervalTime * 1000)
        },
        //角色DOT技能血条和浮动信息控制
        RaidDotBloodControl: function (data, monsterId, skillModel) {
            if (skillModel.SkillOption == 1)//伤害
            {
                var _currentMonsterObj = $("#monsterProgress_h_" + monsterId + "");
                var _monsterHv = parseInt(_currentMonsterObj.attr("hv"));
                if (data.Data.HealthValue <= 0) {
                    //直接血条清0，
                    _currentMonsterObj.css("width", "0%");
                } else {
                    _currentMonsterObj.css("width", (data.Data.HealthValue / _monsterHv).toPercent());
                }
                //浮动战斗文字//暴击这个问题，需要在这个时候独立注册
                var _monsterModel = RaidModel.Model.CreateMonsterModel("monster_" + monsterId);
                FloatTextClass.InitDotMonsterObj(monsterId, data.Data.IsBj);
                FloatTextClass.FloatNum(_monsterModel.JqueryObj, data.Data.HurtValue, 2);

                //判断是否死了。死了就销毁这个对象
                if (data.Data.IsDead == 1)
                    _currentMonsterObj.parent().parent().css("visibility", "hidden");//不销毁，隐藏，否则浮动战斗插件有BUG
            } else {
                //角色治疗DOT
                var roleHvObj = $("#roleProgress_h");

                if (data.Data.HealthValue / parseInt(roleHvObj.attr("hv")) >= 1)
                    roleHvObj.css("width", "100%");
                else
                    roleHvObj.css("width", (data.Data.HealthValue / parseInt(roleHvObj.attr("hv"))).toPercent());
                //浮动战斗文字//暴击这个问题，需要在这个时候独立注册

                FloatTextClass.InitRoleObj(data.Data.IsBj);
                FloatTextClass.FloatNum($("#zhujiao"), data.Data.BeTreatedValue, 1);

            }
            //判断是否胜利
            if (data.Data.FightStatus == 1) {
                //--胜利逻辑
                _fightStatus = 1;
                if (!_intervalLock) {
                    _intervalLock = true;
                    this.ReudltHandle();
                }

            }
        },
        //战斗结果处理
        ReudltHandle: function () {
            var fightId = $("#fightId").val();
            var loadingIndex = ToolManager.Layer.Loding("结果计算中.....");
            webExpress.utility.ajax.request("/Raid/RaidResultHandle?token=" + ToolManager.Common.Token(), { "fightId": fightId, "heroId": UserBase.Status.HeroId }, function (data) {
                layer.closeAll("loading");
                if (data.IsSuccess) {
                    var htmlArr = [];
                    htmlArr.push('<div class="resultMsg">');
                    if (data.Data.FightStatus == 1) {
                        htmlArr.push('<div class="resultShow"><img src="/Images/shengli.png" /></div>');
                       htmlArr.push(RaidFight.Instance.CreateFightResultMsgHtml(data));
                        if (data.Data.Props.length > 0) {
                            htmlArr.push('<div class="resultProp">');
                            for (var i = 0; i < data.Data.Props.length; i++) {
                                htmlArr.push(' <p><img src="' + data.Data.Props[i].ImgPath + '" />  <span>' + data.Data.Props[i].PropName + 'x' + data.Data.Props[i].Num + '</span></p>');
                            }
                            htmlArr.push('</div>');
                        }

                    } else {
                        htmlArr.push('<div class="resultShow"><img src="/Images/shibai.png" /></div>');
                        htmlArr.push(RaidFight.Instance.CreateFightResultMsgHtml(data));
                    }
                    htmlArr.push(' <div><a href="javascript:void(0);"><img id="closeResult" src="/Images/queding.png"/></a></div>');
                    htmlArr.push('</div>');
                    var resultScreen = layer.open({
                        type: 1,
                        content: htmlArr.join(''),
                        anim: 'up',
                        style: 'position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;overflow:auto'
                    });
                    //更新状态信息
                    UserBase.Common.SyncLoadUserInfoModelAndEqs();
                    //更新背包信息
                    UserBase.Common.SyncLoadUserBackPack();
                    
                    //背景创建
                    //调整样式冲突
                    $(".layui-m-layercont").css("text-align", "center").css("padding","50px");
                    if(data.Data.FightStatus == 1)
                        $(".layui-m-layerchild").css("background-image", "url('/Images/resultbg.png')").css("background-size", "100% 100%");//结果背景
                } else {
                    alert("数据异常");
                }
            });
        },
        ///创建战斗胜利后，关于角色的信息数据
        CreateFightResultMsgHtml: function (data) {
            var htmlArr = [];
            htmlArr.push('<div class="resultRole">');
            htmlArr.push(' <p><img height="20" width="20" src="/Images/jingyan.png" /><span>获得' + data.Data.ExValues + '经验</span></p>');
            htmlArr.push('<p><img height="20" width="20" src="/Images/jingyan.png" /><span>获得' + data.Data.PotentialValues + '历练值</span></p>');
            htmlArr.push('<p><img height="20" width="20" src="/Images/jinbi.png" /> <span>获得' + data.Data.Money + '个金币</span> </p>');
            htmlArr.push('</div>');
            if (data.Data.IsLevelUp == 1) {
                htmlArr.push('<div class="roleLevel"><img height="20" width="20" src="/Images/shengji.png" /><span>角色升到' + data.Data.GameLevel + '级</span></div>');
            }
            return htmlArr.join('');
        },
        ////怪实际攻击或治疗动画执行完毕，控制血条和判定的回调函数，因为回调函数不允许带参数
        RaidMonsterBloodControlCall: function (resModel) {
            return function () {
                RaidFight.Instance.RaidMonsterBloodControl(resModel);
            }
        },
        //怪攻击或治疗动画执行完毕，控制血条和判定的回调函数
        RaidMonsterBloodControl: function (resModel) {//status.1。怪显示数值。0不显示

            //角色血蓝控制
            var roleHvObj = $("#roleProgress_h");

            if (resModel.HealthValue / parseInt(roleHvObj.attr("hv")) >= 1)
                roleHvObj.css("width", "100%");
            else
                roleHvObj.css("width", (resModel.HealthValue / parseInt(roleHvObj.attr("hv"))).toPercent());
            FloatTextClass.InitRoleObj(0);
            FloatTextClass.FloatNum($("#zhujiao"), resModel.HurtValue, 2);
            //判断是否胜利
            if (resModel.IsDead == 1) {
                //--失败
                _fightStatus = -1;
                if (!_intervalLock) {
                    _intervalLock = true;
                    this.ReudltHandle();
                }
            }

        },
        //角色实际攻击或治疗动画执行完毕，控制血条和判定的回调函数，因为回调函数不允许带参数
        RaidBloodControlCall: function (resModel, optionType, skillType) {
            return function () {
                RaidFight.Instance.RaidBloodControl(resModel, optionType, skillType);
            }
        },
        //角色攻击或治疗动画执行完毕，控制血条和判定的回调函数
        RaidBloodControl: function (resModel, optionType, status) {//status.1。怪显示数值。0不显示
            //怪血条控制
            var _currentMonsterObj; var _monsterHv;
            if (optionType == 1) {
                for (var i = 0; i < resModel.Monsters.length; i++) {
                    //循环这些怪的血条计算
                    _currentMonsterObj = $("#monsterProgress_h_" + resModel.Monsters[i].Id + "");
                    _monsterHv = parseInt(_currentMonsterObj.attr("hv"));
                    if (resModel.Monsters[i].HealthValue <= 0) {
                        //直接血条清0，
                        _currentMonsterObj.css("width", "0%");
                    } else {
                        _currentMonsterObj.css("width", (resModel.Monsters[i].HealthValue / _monsterHv).toPercent());
                    }
                    //浮动战斗文字//暴击这个问题，需要在这个时候独立注册
                    if (status == 1) {
                        var _monsterModel = RaidModel.Model.CreateMonsterModel("monster_" + resModel.Monsters[i].Id);
                        FloatTextClass.InitMonsterObj(resModel.Monsters[i].IsBj);
                        FloatTextClass.FloatNum(_monsterModel.JqueryObj, resModel.Monsters[i].HurtValue, 2);
                    }
                    //判断是否死了。死了就销毁这个对象
                    if (resModel.Monsters[i].IsDead == 1)
                        _currentMonsterObj.parent().parent().css("visibility", "hidden");//不销毁，隐藏，否则浮动战斗插件有BUG
                }
            }

            //角色血蓝控制
            var roleHvObj = $("#roleProgress_h"); var roleMaObj = $("#roleProgress_m");

            if (resModel.Role.HealthValue / parseInt(roleHvObj.attr("hv")) >= 1)
                roleHvObj.css("width", "100%");
            else
                roleHvObj.css("width", (resModel.Role.HealthValue / parseInt(roleHvObj.attr("hv"))).toPercent());
            if (resModel.Role.MagicValue / parseInt(roleMaObj.attr("mv")) >= 1)
                roleMaObj.css("width", "100%");
            else
                roleMaObj.css("width", (resModel.Role.MagicValue / parseInt(roleMaObj.attr("mv"))).toPercent());
            //角色浮动战斗文字。一次性这里，一定是治疗。
            FloatTextClass.InitRoleObj(resModel.Role.IsBj);
            FloatTextClass.FloatNum($("#zhujiao"), resModel.Role.BeTreatedValue, 1);
            //判断是否胜利
            if (resModel.FightStatus == 1) {
                //--胜利逻辑
                _fightStatus = 1;
                if (!_intervalLock) {
                    _intervalLock = true;
                    this.ReudltHandle();
                }
            }

        },
        InitGuai: function () {
            guaiArr = [];
            //怪物初始化
            $(".monster").each(function () {
                if ($(this).parent().css("visibility") != "hidden")
                    guaiArr.push(RaidModel.Model.CreateMonsterModel($(this).attr("id"), $(this).attr("soft")));
            })
        },
        //冷却时间
        ShowCd: function (jid, ct) {
            var cdHtml = '<div class="cdtime" id="cd_' + jid + '">' + ct + '</div>';
            $("#skill_" + jid + "").after(cdHtml);
            var cdObj = $("#cd_" + jid + "");
            setInterval(function () {
                var restTime = parseInt(cdObj.html()) - 1;
                if (restTime == 0) {
                    cdObj.remove();
                    clearInterval(this);
                } else {
                    cdObj.html(restTime);
                }
            }, 1000)
        },
        //控制怪技能CD
        ControlMonsterSkillCd: function (monster) {
            //从新赋值CD，然后逐渐递减
            $("#monster_" + monster.Id + "").attr("skillCd", monster.SkillCd);
            var obj = $("#monster_" + monster.Id + "");
            var cdInterval = setInterval(function () {
                var restTime = parseInt(obj.attr("skillCd")) - 1;
                if (restTime == 0) {
                    clearInterval(cdInterval);
                }
                obj.attr("skillCd", restTime);
            }, 1000)
        },
        //公共冷却时间
        TriggerPublicCd: function (ptime) {
            _publicCd = false;
            setTimeout(function () {
                _publicCd = true;
            }, ptime)
        }
    };
})();